import { useState, useEffect, useRef } from 'react'

function useCountdown(duration, onFinish = () => {}) {
    const [remainingTime, setRemainingTime] = useState(duration)
    const [isActive, setIsActive] = useState(false)

    const timerRef = useRef<any>(null)

    // 暂停计时器
    const pause = () => {
        clearTimeout(timerRef.current)
        setIsActive(false)
    }

    // 从计时器暂停状态恢复
    const resume = () => {
        setIsActive(true)
    }

    // 重置计时器
    const reset = (duration) => {
        clearTimeout(timerRef.current)
        setIsActive(false)
        setRemainingTime(duration)
    }

    // 更新剩余时间，并保存计时器句柄
    useEffect(() => {
        if (isActive && remainingTime > 0) {
            timerRef.current = setTimeout(() => {
                setRemainingTime((prev) => prev - 1)
            }, 1000)
        } else if (remainingTime === 0) {
            onFinish()
        }

        return () => clearTimeout(timerRef.current)
    }, [duration, isActive, remainingTime, onFinish])

    return { remainingTime, isActive, pause, resume, reset }
}

export default useCountdown
